package com.ashley.phonemsn

import android.Manifest
import android.content.ContentProviderOperation
import android.content.Context
import android.content.pm.PackageManager
import android.database.Cursor
import android.net.Uri
import android.provider.ContactsContract
import android.util.Log
import androidx.core.content.ContextCompat

class ContactManager(private val context: Context) {
    private val TAG = "ContactManager"
    
    // 联系人数据类
    data class Contact(
        val id: String,
        val name: String,
        val phoneNumber: String
    )
    
    // 检查是否有权限读取通讯录
    fun hasReadContactsPermission(): Boolean {
        return ContextCompat.checkSelfPermission(
            context,
            Manifest.permission.READ_CONTACTS
        ) == PackageManager.PERMISSION_GRANTED
    }
    
    // 检查是否有权限写入通讯录
    fun hasWriteContactsPermission(): Boolean {
        return ContextCompat.checkSelfPermission(
            context,
            Manifest.permission.WRITE_CONTACTS
        ) == PackageManager.PERMISSION_GRANTED
    }
    
    // 读取所有联系人
    fun getAllContacts(): List<Contact> {
        if (!hasReadContactsPermission()) {
            Log.e(TAG, "没有读取通讯录权限")
            return emptyList()
        }
        
        val contacts = mutableListOf<Contact>()
        
        try {
            val cursor: Cursor? = context.contentResolver.query(
                ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
                arrayOf(
                    ContactsContract.CommonDataKinds.Phone._ID,
                    ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME,
                    ContactsContract.CommonDataKinds.Phone.NUMBER
                ),
                null,
                null,
                ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME + " ASC"
            )
            
            cursor?.use { cursor ->
                val idIndex = cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone._ID)
                val nameIndex = cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME)
                val numberIndex = cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER)
                
                while (cursor.moveToNext()) {
                    val id = cursor.getString(idIndex)
                    val name = cursor.getString(nameIndex)
                    val number = cursor.getString(numberIndex)
                        .replace("\\D", "") // 只保留数字
                    
                    if (number.isNotEmpty()) {
                        contacts.add(Contact(id, name, number))
                    }
                }
            }
        } catch (e: Exception) {
            Log.e(TAG, "读取通讯录失败: $e")
        }
        
        return contacts
    }
    
    // 添加联系人
    fun addContact(name: String, phoneNumber: String): Boolean {
        if (!hasWriteContactsPermission()) {
            Log.e(TAG, "没有写入通讯录权限")
            return false
        }
        
        try {
            val operations = ArrayList<ContentProviderOperation>()
            
            // 创建raw contact
            val rawContactOperation = ContentProviderOperation.newInsert(
                ContactsContract.RawContacts.CONTENT_URI
            ).withValue(ContactsContract.RawContacts.ACCOUNT_TYPE, null)
                .withValue(ContactsContract.RawContacts.ACCOUNT_NAME, null)
                .build()
            operations.add(rawContactOperation)
            
            // 添加联系人名称
            if (name.isNotEmpty()) {
                val nameOperation = ContentProviderOperation.newInsert(
                    ContactsContract.Data.CONTENT_URI
                ).withValueBackReference(ContactsContract.Data.RAW_CONTACT_ID, 0)
                    .withValue(ContactsContract.Data.MIMETYPE, ContactsContract.CommonDataKinds.StructuredName.CONTENT_ITEM_TYPE)
                    .withValue(ContactsContract.CommonDataKinds.StructuredName.DISPLAY_NAME, name)
                    .build()
                operations.add(nameOperation)
            }
            
            // 添加电话号码
            val numberOperation = ContentProviderOperation.newInsert(
                ContactsContract.Data.CONTENT_URI
            ).withValueBackReference(ContactsContract.Data.RAW_CONTACT_ID, 0)
                .withValue(ContactsContract.Data.MIMETYPE, ContactsContract.CommonDataKinds.Phone.CONTENT_ITEM_TYPE)
                .withValue(ContactsContract.CommonDataKinds.Phone.NUMBER, phoneNumber)
                .withValue(ContactsContract.CommonDataKinds.Phone.TYPE, ContactsContract.CommonDataKinds.Phone.TYPE_MOBILE)
                .build()
            operations.add(numberOperation)
            
            // 执行操作
            context.contentResolver.applyBatch(ContactsContract.AUTHORITY, operations)
            return true
        } catch (e: Exception) {
            Log.e(TAG, "添加联系人失败: $e")
            return false
        }
    }
    
    // 更新联系人
    fun updateContact(contactId: String, name: String, phoneNumber: String): Boolean {
        if (!hasWriteContactsPermission()) {
            Log.e(TAG, "没有写入通讯录权限")
            return false
        }
        
        try {
            // 查找联系人的rawContactId
            val cursor: Cursor? = context.contentResolver.query(
                ContactsContract.Data.CONTENT_URI,
                arrayOf(ContactsContract.Data.RAW_CONTACT_ID),
                "${ContactsContract.Data._ID} = ?",
                arrayOf(contactId),
                null
            )
            
            cursor?.use { cursor ->
                if (cursor.moveToFirst()) {
                    val rawContactId = cursor.getLong(cursor.getColumnIndex(ContactsContract.Data.RAW_CONTACT_ID))
                    
                    val operations = ArrayList<ContentProviderOperation>()
                    
                    // 更新联系人名称
                    operations.add(
                        ContentProviderOperation.newUpdate(ContactsContract.Data.CONTENT_URI)
                            .withSelection(
                                "${ContactsContract.Data.RAW_CONTACT_ID} = ? AND ${ContactsContract.Data.MIMETYPE} = ?",
                                arrayOf(
                                    rawContactId.toString(),
                                    ContactsContract.CommonDataKinds.StructuredName.CONTENT_ITEM_TYPE
                                )
                            )
                            .withValue(ContactsContract.CommonDataKinds.StructuredName.DISPLAY_NAME, name)
                            .build()
                    )
                    
                    // 更新电话号码
                    operations.add(
                        ContentProviderOperation.newUpdate(ContactsContract.Data.CONTENT_URI)
                            .withSelection(
                                "${ContactsContract.Data._ID} = ?",
                                arrayOf(contactId)
                            )
                            .withValue(ContactsContract.CommonDataKinds.Phone.NUMBER, phoneNumber)
                            .build()
                    )
                    
                    // 执行操作
                    context.contentResolver.applyBatch(ContactsContract.AUTHORITY, operations)
                    return true
                }
            }
        } catch (e: Exception) {
            Log.e(TAG, "更新联系人失败: $e")
        }
        return false
    }
    
    // 删除联系人
    fun deleteContact(contactId: String): Boolean {
        if (!hasWriteContactsPermission()) {
            Log.e(TAG, "没有写入通讯录权限")
            return false
        }
        
        try {
            // 查找联系人的rawContactId
            val cursor: Cursor? = context.contentResolver.query(
                ContactsContract.Data.CONTENT_URI,
                arrayOf(ContactsContract.Data.RAW_CONTACT_ID),
                "${ContactsContract.Data._ID} = ?",
                arrayOf(contactId),
                null
            )
            
            cursor?.use { cursor ->
                if (cursor.moveToFirst()) {
                    val rawContactId = cursor.getLong(cursor.getColumnIndex(ContactsContract.Data.RAW_CONTACT_ID))
                    
                    // 删除联系人
                    val result = context.contentResolver.delete(
                        ContactsContract.RawContacts.CONTENT_URI,
                        "${ContactsContract.RawContacts._ID} = ?",
                        arrayOf(rawContactId.toString())
                    )
                    return result > 0
                }
            }
        } catch (e: Exception) {
            Log.e(TAG, "删除联系人失败: $e")
        }
        return false
    }
    
    // 搜索联系人
    fun searchContacts(query: String): List<Contact> {
        if (!hasReadContactsPermission()) {
            Log.e(TAG, "没有读取通讯录权限")
            return emptyList()
        }
        
        val contacts = mutableListOf<Contact>()
        
        try {
            val cursor: Cursor? = context.contentResolver.query(
                ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
                arrayOf(
                    ContactsContract.CommonDataKinds.Phone._ID,
                    ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME,
                    ContactsContract.CommonDataKinds.Phone.NUMBER
                ),
                "${ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME} LIKE ? OR ${ContactsContract.CommonDataKinds.Phone.NUMBER} LIKE ?",
                arrayOf("%$query%", "%$query%"),
                ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME + " ASC"
            )
            
            cursor?.use { cursor ->
                val idIndex = cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone._ID)
                val nameIndex = cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME)
                val numberIndex = cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER)
                
                while (cursor.moveToNext()) {
                    val id = cursor.getString(idIndex)
                    val name = cursor.getString(nameIndex)
                    val number = cursor.getString(numberIndex)
                        .replace("\\D", "") // 只保留数字
                    
                    if (number.isNotEmpty()) {
                        contacts.add(Contact(id, name, number))
                    }
                }
            }
        } catch (e: Exception) {
            Log.e(TAG, "搜索联系人失败", e)
        }
        
        return contacts
    }
}